<template>
  <div>
    <div ref="pieChart" style="width: 100%; height: 100%"></div>
  </div>
</template>


<script setup lang="ts">

import { Toast } from "/@/utils/Message";
import { reactive, ref } from "vue";
import { onMounted,watch } from "vue";
import * as echarts from "echarts";
interface propsInterface { 
  colorS: any[],
  titleTest: Array<string>,
  data:any[]
}
const props = withDefaults(defineProps<propsInterface>(), {
  colorS: () => [],
  titleTest: () => [],
  data: ()=>[]
})


const pieChart = ref(); // 使用ref创建虚拟DOM引用，使用时用main.value

onMounted(() => {
  init();
});
watch(props.data, (val, newvalue) => { 
  if (props.data.length !== 0) {
    init();
  }
}, {deep:true})

function init() {
  // 基于准备好的dom，初始化echarts实例
  const chart = echarts.init(pieChart.value);

  // 指定图表的配置项和数据
  let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
  let rightNum = '20'
  let sizeNum = '14'
  if(htmlWidth >700) {
    rightNum = '19%'
    sizeNum = '24'
  }
  if(htmlWidth <360){
    rightNum = '8%'
    sizeNum = '10'
  }
  const option = {
    color:props.colorS,  //['#C1EBDD', '#FFC851', '#5A5476', '#1869A0', '#FF9393'],
    tooltip: {
      trigger: "item",
    },
    legend: {
        top: 'center',
        right: rightNum,
        bottom: 20,
        textStyle: {
          fontSize: sizeNum
        },
        orient: 'vertical',
        selectedMode: false,
        formatter: (name) => {
              let total = 0;
              let tarValue;
              for (let i = 0; i < props.data.length; i++) {
                total += props.data[i].value;
                if (props.data[i].name == name) {
                  tarValue = props.data[i].value;
                }
              }
              return `${name}  ${tarValue}`;
          },
    },
    series: [
      {
        // name: "保单件数",
        type: "pie",
        radius: ["40%", "70%"],
        center: ['30%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 3,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: false,
          formatter: '{c}',
          position: 'inner',
          alignTo: 'labelLine'
        },
        labelLine: {
          show: false,
        },
         data:props.data //[
        //   { value: 1048, name: props.data[0]},
        //   { value: 735, name:  props.data[1]},
        //   { value: 580, name:  props.data[2]},
        //   { value: 484, name:  props.data[3]},
        // ],
      },
    ],
  };

  // 使用刚指定的配置项和数据显示图表。
  chart.setOption(option);
}
</script>

<style lang="less" scoped>
</style>
  
  